package com.glory.hzlionpda.activity;

import android.os.Handler;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hzlionpda.R;
import com.glory.hzlionpda.adapter.EqpThingListAdapter;
import com.glory.hzlionpda.adapter.InputDataListAdapter;
import com.glory.hzlionpda.adapter.LotThingListAdapter;
import com.glory.hzlionpda.adapter.MessageListAdapter;
import com.glory.hzlionpda.adapter.TrackInCarryListAdapter;
import com.glory.hzlionpda.base.App;
import com.glory.hzlionpda.base.Constant;
import com.glory.hzlionpda.bean.BaseBean;
import com.glory.hzlionpda.bean.CarryBean;
import com.glory.hzlionpda.bean.EqpBean;
import com.glory.hzlionpda.bean.InputDataBean;
import com.glory.hzlionpda.bean.LotBean;
import com.glory.hzlionpda.bean.MateriaBean;
import com.glory.hzlionpda.bean.MessageBean;
import com.glory.hzlionpda.bean.MessageObject;
import com.glory.hzlionpda.callback.ChangeCallback;
import com.glory.hzlionpda.dialog.MessageDialog;
import com.glory.hzlionpda.utils.NetUtils;
import com.glory.hzlionpda.utils.VibratorUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.base.FreeUI_BaseActivity;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextCallback;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class StartLotActivity extends FreeUI_BaseActivity {

    @BindView(R.id.tvStatus)
    TextView tvStatus;
    @BindView(R.id.tvMode)
    TextView tvMode;
    @BindView(R.id.toggleButton)
    ToggleButton toggleButton;
    @BindView(R.id.tvNum)
    TextView tvNum;
    @BindView(R.id.tvDevice)
    TextView tvDevice;
    @BindView(R.id.tvRecipeName)
    TextView tvRecipeName;
    @BindView(R.id.tvCurrentStation)
    TextView tvCurrentStation;
    @BindView(R.id.tvNextStation)
    TextView tvNextStation;
    @BindView(R.id.ivDownArrow)
    ImageView ivDownArrow;
    @BindView(R.id.rlInfo)
    RelativeLayout rlInfo;
    @BindView(R.id.rvThingList)
    RecyclerView rvThingList;
    @BindView(R.id.tvInputTitle)
    TextView tvInputTitle;
    @BindView(R.id.tvChoose)
    TextView tvChoose;
    @BindView(R.id.ivDownArrow2)
    ImageView ivDownArrow2;
    @BindView(R.id.tvSubmitInput)
    TextView tvSubmitInput;
    @BindView(R.id.rlInput)
    RelativeLayout rlInput;
    @BindView(R.id.rvInputList)
    RecyclerView rvInputList;
    @BindView(R.id.rvEqpList)
    RecyclerView rvEqpList;
    @BindView(R.id.rlMore)
    RelativeLayout rlMore;
    @BindView(R.id.rvMessageList)
    RecyclerView rvMessageList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvRunCheckNote)
    TextView tvRunCheckNote;
    @BindView(R.id.tvUser)
    TextView tvUser;
    @BindView(R.id.etEqpItem)
    FreeUI_ClearEditText etEqpItem;
    @BindView(R.id.llLotThing)
    LinearLayout llLotThing;
    @BindView(R.id.svMain)
    NestedScrollView svMain;
    @BindView(R.id.rvCarryList)
    RecyclerView rvCarryList;
    @BindView(R.id.llCarry)
    LinearLayout llCarry;
    @BindView(R.id.tvEqpRecipeName)
    TextView tvEqpRecipeName;
//    @BindView(R.id.tbManyLots)
//    ToggleButton tbManyLots;
    @BindView(R.id.etLotId)
    FreeUI_ClearEditText etLotId;
    @BindView(R.id.etCarryId)
    FreeUI_ClearEditText etCarryId;
    @BindView(R.id.tbMaskId)
    ToggleButton tbMaskId;
    @BindView(R.id.etMask)
    FreeUI_ClearEditText etMask;


    private String lots;
    private Timer timer;
    private List<MessageObject> messageEntityList;
    private MessageListAdapter messageListAdapter;
    private LotBean currentLotBean;
    private Animation animation, animationDismiss;
    private LotThingListAdapter lotThingListAdapter;
    private EqpThingListAdapter eqpThingListAdapter;
    private FreeUI_GeneralFragmentDialog changeDialog;
    private InputDataListAdapter inputDataListAdapter;
    private String eqpId = "";
    private List<String> alertMessageIdList = new ArrayList<>();
    private boolean isVirating = false;
    private TrackInCarryListAdapter trackInCarryListAdapter;
    private String firstRecipe = "";

    @Override
    protected void onPause() {
        super.onPause();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    @OnClick({R.id.tvRemove, R.id.rlInfo, R.id.rlInput,})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvRemove:
                List<CarryBean> removeList = new ArrayList<>();
                for (CarryBean carryBean : trackInCarryListAdapter.getData()) {
                    if (carryBean.isSelect()) {
                        removeList.add(carryBean);
                    }
                }
                if (removeList.size() > 0) {
                    trackInCarryListAdapter.clearPos();
                    trackInCarryListAdapter.getData().removeAll(removeList);
                    trackInCarryListAdapter.notifyDataSetChanged();
                } else {
                    showToast("未勾选，不能移除", false);
                }
                break;
            case R.id.rlInput:
                if (rvInputList.getVisibility() == View.VISIBLE) {
                    if (animation == null) {
                        animation = new RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF,
                                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animation.setDuration(500);
                        animation.setFillAfter(true);
                    }
                    ivDownArrow2.startAnimation(animation);
                    rvInputList.setVisibility(View.GONE);
                } else {
                    if (animationDismiss == null) {
                        animationDismiss = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF,
                                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animationDismiss.setDuration(500);
                        animationDismiss.setFillAfter(true);
                    }
                    ivDownArrow2.startAnimation(animationDismiss);
                    rvInputList.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.rlInfo:
//                if (rvThingList.getVisibility() == View.VISIBLE) {
//                    if (animationDismiss == null) {
//                        animationDismiss = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF,
//                                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//                        animationDismiss.setDuration(500);
//                        animationDismiss.setFillAfter(true);
//                    }
//                    ivDownArrow.startAnimation(animationDismiss);
//                    rvThingList.setVisibility(View.GONE);
//                } else {
//                    if (animation == null) {
//                        animation = new RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF,
//                                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
//                        animation.setDuration(500);
//                        animation.setFillAfter(true);
//                    }
//                    ivDownArrow.startAnimation(animation);
//                    rvThingList.setVisibility(View.VISIBLE);
//                }
                break;
        }
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_start_lot;
    }

    @Override
    protected void initView() {
        tvUser.setText(Constant.CURRENT_USER);
        freeUI_titleView.setTitle("批次开始");
        freeUI_titleView.setRightListener("开始作业", view -> requestTrackIn());

        rvInputList.setLayoutManager(new LinearLayoutManager(StartLotActivity.this));
        rvInputList.setItemAnimator(new DefaultItemAnimator());
        rvInputList.addItemDecoration(new DividerItemDecoration(StartLotActivity.this, 1));

        rvThingList.setLayoutManager(new LinearLayoutManager(StartLotActivity.this));
        rvThingList.setItemAnimator(new DefaultItemAnimator());
        rvThingList.addItemDecoration(new DividerItemDecoration(StartLotActivity.this, 1));

        rvEqpList.setLayoutManager(new LinearLayoutManager(StartLotActivity.this));
        rvEqpList.setItemAnimator(new DefaultItemAnimator());
        rvEqpList.addItemDecoration(new DividerItemDecoration(StartLotActivity.this, 1));

        rvMessageList.setLayoutManager(new LinearLayoutManager(StartLotActivity.this));
        rvMessageList.setItemAnimator(new DefaultItemAnimator());
        rvMessageList.addItemDecoration(new DividerItemDecoration(StartLotActivity.this, 1));

        rvCarryList.setLayoutManager(new LinearLayoutManager(StartLotActivity.this));
        rvCarryList.setItemAnimator(new DefaultItemAnimator());
        rvCarryList.addItemDecoration(new DividerItemDecoration(StartLotActivity.this, 1));

        trackInCarryListAdapter = new TrackInCarryListAdapter(null);
        trackInCarryListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        trackInCarryListAdapter.isFirstOnly(true);
        rvCarryList.setAdapter(trackInCarryListAdapter);

        lotThingListAdapter = new LotThingListAdapter(null);
        lotThingListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        lotThingListAdapter.isFirstOnly(true);
        rvThingList.setAdapter(lotThingListAdapter);

        eqpThingListAdapter = new EqpThingListAdapter(null);
        eqpThingListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        eqpThingListAdapter.isFirstOnly(true);
        rvEqpList.setAdapter(eqpThingListAdapter);
    }

    private void requestTrackIn() {
        if (etEqpItem.getText().toString().trim().length() == 0) {
            showToast("请先扫描设备编号", false);
            return;
        }
        boolean isOk = true;
        for (InputDataBean inputDataBean : inputDataListAdapter.getData()) {
            if (inputDataBean.getXMMVALUE().length() == 0) {
                isOk = false;
                break;
            }
        }
        if (!isOk) {
            showToast("请完整填写运行记录", false);
            return;
        }

        if (llCarry.getVisibility() == View.VISIBLE && trackInCarryListAdapter.getData().size() == 0) {
            showToast("多批次模式请添加多批次", false);
            return;
        }
        if (llCarry.getVisibility() == View.VISIBLE) {
            List<Boolean> booleanList = new ArrayList<>();
            String[] arrayLot = lots.split(",");
            for (String str : arrayLot) {
                boolean firstLotIsIn = false;
                for (CarryBean carryBean : trackInCarryListAdapter.getData()) {
                    if (carryBean.getLOTID().equals(str)) {
                        firstLotIsIn = true;
                        break;
                    }
                }
                booleanList.add(firstLotIsIn);
            }
            boolean isAllOk = true;
            for (Boolean b : booleanList) {
                if (!b) {
                    isAllOk = false;
                    break;
                }
            }
            if (!isAllOk) {
                showToast("多批次模式载具列表必须包含所有初始扫描批次", false);
                return;
            }
        }
        String maskId = etMask.getText().toString().trim();
        if (etMask.getVisibility() == View.VISIBLE) {
            if (FreeApi_StringUtils.isEmpty(maskId)) {
                showToast("请扫描模板号", false);
                return;
            } else {
                if (!currentLotBean.getMASKID().contains(maskId)) {
                    showToast("请扫描正确范围内的模板号", false);
                    return;
                }
            }
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("EQPID", etEqpItem.getText().toString().trim());
            jsonObject.put("OPID", Constant.CURRENT_USER);
            jsonObject.put("LOTID", lots);
            jsonObject.put("ISRUNCHECK", "Y");
            if (etMask.getVisibility() == View.VISIBLE) {
                jsonObject.put("MASKID", maskId);
            } else {
                jsonObject.put("MASKID", currentLotBean.getMASKID());
            }
            jsonObject.put("RUNCHECKNOTE", tvRunCheckNote.getText().toString());
            jsonObject.put("RUNCHECKLIST", new JSONArray(new Gson().toJson(inputDataListAdapter.getData())));
            if (llCarry.getVisibility() == View.VISIBLE) {
                jsonObject.put("CARRIERLIST", new JSONArray(new Gson().toJson(trackInCarryListAdapter.getData())));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestGetNet("TRACKINREQUEST", this, jsonObject, new FreeUI_DialogEntityCallBack<BaseBean>(
                new TypeToken<BaseBean>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<BaseBean> response) {
                if (response.body().isSuccess(getApplicationContext())) {
                    showToast("进站成功", true);
                    StartLotActivity.this.finish();
                }
            }

            @Override
            public void onError(Response<BaseBean> response) {
                super.onError(response);
                loadError(response.getException(), "TRACKINREQUEST");
            }
        });
    }

    @Override
    protected void initData() {
        lots = getIntent().getStringExtra("lots");

        requestAllLotInfo();

        messageEntityList = new ArrayList<>();
        messageListAdapter = new MessageListAdapter(messageEntityList);
        messageListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        messageListAdapter.isFirstOnly(true);
        rvMessageList.setAdapter(messageListAdapter);
        etEqpItem.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    if (charSequence.length() > 0) {
                        svMain.post(new Runnable() {
                            @Override
                            public void run() {
                                svMain.scrollTo(0, rlMore.getTop());
                            }
                        });
                        eqpId = charSequence.toString();
                        requestLotInfo();
                    } else {
                        showToast("扫描信息有误", false);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

//        tbManyLots.setOnCheckedChangeListener((compoundButton, b) -> llCarry.setVisibility(b ? View.VISIBLE : View.GONE));
        tbMaskId.setOnCheckedChangeListener((compoundButton, b) -> {
            etMask.setText("");
            etMask.setVisibility(b ? View.VISIBLE : View.GONE);
        });
        etLotId.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    if (charSequence.length() > 0) {
                        boolean isHave = false;
                        for (CarryBean carryBean : trackInCarryListAdapter.getData()) {
                            if (carryBean.getLOTID().equals(charSequence.toString())) {
                                isHave = true;
                                break;
                            }
                        }
                        if (isHave) {
                            showToast("LotId已存在列表中", false);
                        } else {
                            requestLotVerify(charSequence.toString());
                        }
                    } else {
                        showToast("扫描信息有误", false);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        etCarryId.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    if (charSequence.length() > 0) {
                        String lotId = etLotId.getText().toString().trim();
                        if (lotId.length() == 0) {
                            showToast("请先扫描批次号", false);
                            etLotId.requestFocus();
                            etCarryId.setText("");
                        } else {
                            CarryBean carryBean = new CarryBean();
                            carryBean.setLOTID(lotId);
                            carryBean.setSEQ(String.valueOf(trackInCarryListAdapter.getData().size() + 1));
                            carryBean.setCARRIDERID(charSequence.toString());
                            trackInCarryListAdapter.addData(carryBean);
                            etLotId.requestFocus();
                            etCarryId.setText("");
                            etLotId.setText("");
                        }
                    } else {
                        showToast("扫描信息有误", false);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        return new FreeUI_AddViewEntity(getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY), llMain);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
    }

    private void requestAllLotInfo() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("LOTID", lots);
            jsonObject.put("OPID", Constant.CURRENT_USER);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestGetNet("LOTPROCESSINFOQUEST", this, jsonObject, new FreeUI_DialogEntityCallBack<EqpBean>(
                new TypeToken<EqpBean>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<EqpBean> response) {
                if (response.body().isSuccess(getApplicationContext())) {
                    if (response.body() != null) {
                        setEqpInfo(response.body());
                    }
                } else {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            StartLotActivity.this.finish();
                        }
                    }, 2000);
                }
            }

            @Override
            public void onError(Response<EqpBean> response) {
                super.onError(response);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        StartLotActivity.this.finish();
                    }
                }, 2000);
                loadError(response.getException(), "LOTPROCESSINFOQUEST");
            }
        });
    }

    private void requestLotInfo() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("EQPID", eqpId);
            jsonObject.put("OPID", Constant.CURRENT_USER);
            jsonObject.put("LOTID", lots);
            jsonObject.put("MASKID", etMask.getText().toString().trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestGetNet("LOTINFOREQUEST", this, jsonObject, new FreeUI_DialogEntityCallBack<LotBean>(
                new TypeToken<LotBean>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<LotBean> response) {
                if (response.body().isSuccess(getApplicationContext())) {
                    MessageDialog messageDialog = new MessageDialog();
                    messageDialog.setCallBack(() -> startTimer(), eqpId);
                    messageDialog.show(getSupportFragmentManager(), "message_dialog");
                    currentLotBean = response.body();
                    if (currentLotBean.getISLOTS().equalsIgnoreCase("Y")) {
                        llCarry.setVisibility(View.VISIBLE);
                    } else {
                        llCarry.setVisibility(View.GONE);
                    }
                    tvRecipeName.setText(currentLotBean.getRECIPE());
                    tvEqpRecipeName.setText(currentLotBean.getEQPRECIPE());
                    tvNum.setText(currentLotBean.getWAFERQTY());
                    tvStatus.setText(currentLotBean.getEQPSTATUS());
                    tvCurrentStation.setText(currentLotBean.getNOWSTEPDESC());
                    tvNextStation.setText(currentLotBean.getNEXTSTEPDESC());
                    tvRunCheckNote.setText(currentLotBean.getRUNCHECKNOTE());
                    tvDevice.setText(currentLotBean.getPARTNAME());
                    inputDataListAdapter.setNewData(currentLotBean.getRUNCHECKLIST());
                    lotThingListAdapter.setNewData(currentLotBean.getWAFERLIST());
                    eqpThingListAdapter.setNewData(currentLotBean.getMATERIALIST());
                } else {
                    etEqpItem.setText("");
                }
            }

            @Override
            public void onError(Response<LotBean> response) {
                super.onError(response);
                loadError(response.getException(), "LOTINFOREQUEST");
            }
        });
    }

    private void requestLotVerify(String lot) {
        if (FreeApi_StringUtils.isEmpty(eqpId)) {
            showToast("请先扫描设备ID", false);
            return;
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("LOTID", lot);
            jsonObject.put("OPID", Constant.CURRENT_USER);
            jsonObject.put("EQPID", eqpId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestGetNet("LOTOUTREQUEST", this, jsonObject, new FreeUI_DialogEntityCallBack<LotBean>(
                new TypeToken<LotBean>() {
                }.getType(), getSupportFragmentManager(), this) {
            @Override
            public void onSuccess(Response<LotBean> response) {
                if (response.body().isSuccess(getApplicationContext())) {
                    LotBean lotBean = response.body();
                    if (lotBean != null) {
                        if (trackInCarryListAdapter.getData().size() == 0) {
                            firstRecipe = lotBean.getRECIPE();
                        }
                        if (!firstRecipe.equals(lotBean.getRECIPE())) {
                            showToast("RECIPE不匹配，请重新扫描", false);
                            etLotId.setText("");
                            etLotId.requestFocus();
                        } else {
                            etCarryId.requestFocus();
                        }
                    }
                } else {
                    showToast("服务器返回FAIL，请重新扫描", false);
                    etLotId.setText("");
                    etLotId.requestFocus();
                }
            }

            @Override
            public void onError(Response<LotBean> response) {
                super.onError(response);
                showToast("请求服务器失败，请重新扫描", false);
                etLotId.setText("");
                etLotId.requestFocus();
                loadError(response.getException(), "LOTOUTREQUEST");
            }
        });
    }

    private void setEqpInfo(final EqpBean eqpBean) {
        tvNum.setText(eqpBean.getNOWLOTNUM());
        tvDevice.setText(eqpBean.getPARTNAME());
        tvRecipeName.setText(eqpBean.getRECIPE());
        tvEqpRecipeName.setText(eqpBean.getEQPRECIPE());
        tvCurrentStation.setText(eqpBean.getNOWSTEPDESC());
        tvNextStation.setText(eqpBean.getNEXTSTEPDESC());
        if (eqpBean.getWAFERLIST().size() > 0) {
            lotThingListAdapter.setNewData(eqpBean.getWAFERLIST());
        }
        if (eqpBean.getISLOTS().equalsIgnoreCase("Y")) {
            llCarry.setVisibility(View.VISIBLE);
        } else {
            llCarry.setVisibility(View.GONE);
        }
        refreshInputAdapter(eqpBean.getRUNCHECKLIST());
        eqpThingListAdapter.setNewData(eqpBean.getMATERIALIST());
        eqpThingListAdapter.setCallBack(new ChangeCallback() {
            @Override
            public void onSuccess(final MateriaBean bean) {
                final List<MateriaBean> changeList = new ArrayList<>();
                changeList.add(bean);
                String tips = "请扫描要更换的" + bean.getMATERIANAME() + "物料编码";
                changeDialog = FreeApi_DialogUtils.getScanDialog(getApplicationContext(), tips, new FreeUI_TextCallback() {
                    @Override
                    public void onSuccess(String s) {
                        bean.setMATERIAVALUE(s);
                        JSONObject jsonObject = new JSONObject();
                        try {
                            JSONArray jsonArray = new JSONArray(new Gson().toJson(changeList));
                            jsonObject.put("EQPID", eqpBean.getNOWEQPID());
                            jsonObject.put("OPID", Constant.CURRENT_USER);
                            jsonObject.put("MATERIALIST", jsonArray);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        NetUtils.requestGetNet("MATERIALCHANGEREPORT", this, jsonObject, new FreeUI_DialogEntityCallBack<BaseBean>(
                                new TypeToken<BaseBean>() {
                                }.getType(), getSupportFragmentManager(), this) {
                            @Override
                            public void onSuccess(Response<BaseBean> response) {
                                if (response.body().isSuccess(getApplicationContext())) {
                                    eqpThingListAdapter.notifyDataSetChanged();
                                    showToast("更换成功", true);
                                    changeDialog.dismiss();
                                }
                            }

                            @Override
                            public void onError(Response<BaseBean> response) {
                                super.onError(response);
                                loadError(response.getException(), "MATERIALCHANGEREPORT");
                            }
                        });
                    }
                });
                changeDialog.show(getSupportFragmentManager(), "changeDialog");
            }
        });
    }

    private void startTimer() {
        if (timer == null) {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    requestMessageData();
                }
            }, 0, 2000);
        }
    }

    private void refreshInputAdapter(List<InputDataBean> runchecklist) {
        inputDataListAdapter = new InputDataListAdapter(runchecklist);
        inputDataListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        inputDataListAdapter.isFirstOnly(true);
        rvInputList.setAdapter(inputDataListAdapter);
    }

    private void requestMessageData() {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("EQPID", eqpId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtils.requestGetNet("LOGMESSAGERQUEST", this, jsonObject, new FreeUI_EntityCallBack<MessageBean>(
                new TypeToken<MessageBean>() {
                }.getType()) {
            @Override
            public void onSuccess(Response<MessageBean> response) {
                if (response.body().isSuccess(getApplicationContext())) {
                    messageEntityList.clear();
                    messageEntityList.addAll(response.body().getLOGMESSAGETEXTLIST());
                    messageListAdapter.notifyDataSetChanged();
                    dealMessage(response.body().getLOGMESSAGETEXTLIST());
                }
            }

            @Override
            public void onError(Response<MessageBean> response) {
                super.onError(response);
            }
        });
    }

    private void dealMessage(List<MessageObject> data) {
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getISALERT().equals("1")) {
                boolean isShow = false;
                for (String str : alertMessageIdList) {
                    if (str.equals(data.get(i).getMESSAGEID())) {
                        isShow = true;
                        break;
                    }
                }
                if (!isShow) {
                    alertMessageIdList.add(data.get(i).getMESSAGEID());
                    FreeUI_GeneralFragmentDialog warnDialog = FreeApi_DialogUtils.getConfirmDialog(App.app, "我知道了", data.get(i).getLOGMESSAGETEXT(), new FreeUI_CommonCallback() {
                        @Override
                        public void onSuccess() {

                        }
                    });
                    warnDialog.setCallBack(new FreeUI_CommonCallback() {
                        @Override
                        public void onSuccess() {
                            if (isVirating) {
                                isVirating = false;
                                VibratorUtils.virateCancle(StartLotActivity.this);
                            }
                        }
                    });
                    if (!isVirating) {
                        isVirating = true;
                        VibratorUtils.vibrate(StartLotActivity.this, new long[]{500, 1000}, 0);
                    }
                    warnDialog.show(getSupportFragmentManager(), "UnLock_DIALOG");
                }
            }
        }
    }
}

